const express = require('express')
const { SerialPort } = require('serialport')
const fs = require('fs')
const dayjs = require('dayjs')
const iconv = require('iconv-lite')
const config = require('./config')

const app = express()

SerialPort.list().then(ports => {
    const coms = ports.map(i => i.path)
    console.log('串口列表: ==> ', coms.toString(), config.path)
})


// 实例化 初始化
const instance = new SerialPort({
    path: config.path,
    baudRate: config.baudRate,
    autoOpen: config.autoOpen,
    encoding: config.encoding,
    dataBits: config.dataBits,
}, err => {
    if(err) {
        return console.log(err.message)
    }
})


instance.open(err => {
    if(err) {
        console.log('Error on open: ', err.message);
        return
    }

    console.log('port opened ' )


})

// 收到信息
instance.on('data', data => {
    const str = iconv.decode(data, 'gbk')
    console.log('data: ', str)
   saveLog(str + '\n')
})

// 保存日志
function saveLog(content) {
    return new Promise((resolve, reject) => {

    const fileName = `${dayjs().format('YYYY-MM-DD')}_${config.path}.txt`
    const path = `./logs/${fileName}`

        fs.writeFile(path, content, {flag: 'a'}, err => {
            if (err) {
                console.log('写日志错误: ', err.toString())
                reject(err)
                return
            }
            resolve()
        })
    })
}

app.listen(3002, () => {
    console.log('listen http://logalhost:3002');
})
